package com.piesat.quake.common.websocket;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
//接口路径 ws://localhost:8087/websocket/userId
@ServerEndpoint("/ws/{userId}")
public class WebSocket {

    //与某个客户端连接会话，需要通过它来给客户端发送数据
    private Session session;
    //用户ID
    private String userId;

    //用来存放每个客户端对应的MyWebSocket对象
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    //用来存在线连接用户信息
    private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    /**
     * 链接成功调用的方法
     *
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSockets.add(this);
        sessionPool.put(userId, session);
        log.info("websocket有新的连接，总数为:{}", webSockets.size());
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSockets.remove(this);
        sessionPool.remove(this.userId);
        log.info("websocket有链接断开，总数为：{}", webSockets.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("websocket收到客户端消息：{}", message);
    }

    /**
     * 广播消息
     *
     * @param message
     */
    public void sendAllMessage(String message) {
        log.info("websocket广播消息:{}", message);
        for (WebSocket webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                log.error("websocket广播消息出错：{}", e.getMessage());
            }
        }
    }

    public void sendAllTopicMessage(String topic, String message) {
        log.info("websocket广播主题{}消息:{}", topic, message);
        for (WebSocket webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    Map<String, String> body = new HashMap<>();
                    body.put(topic, message);
                    webSocket.session.getAsyncRemote().sendText(JSONObject.toJSONString(body));
                }
            } catch (Exception e) {
                log.error("websocket广播主题{}消息出错：{}", topic, e.getMessage());
            }
        }
    }

    /**
     * 单点消息
     *
     * @param userId
     * @param message
     */
    public void sendOneMessage(String userId, String message) {
        log.info("websocket单点消息：{}", message);
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                log.error("websocket单点消息出错：{}", e.getMessage());
            }
        }
    }

    /**
     * 此为多人消息
     *
     * @param userIds
     * @param message
     */
    public void sendMoreMessage(String[] userIds, String message) {
        log.info("websocket多人消息：{}", message);
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    log.error("websocket多人消息出错：{}", e.getMessage());
                }
            }
        }
    }
}
